package com.example.myapplication1;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import java.util.List;

public class CourseAdapter extends RecyclerView.Adapter<CourseAdapter.CourseViewHolder> {
    private List<Course> mCourseList;
    private Context mContext;
    private OnCourseClickListener mListener;

    public CourseAdapter(Context context, List<Course> courseList) {
        mContext = context;
        mCourseList = courseList;
    }

    @NonNull
    @Override
    public CourseViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.item_course, parent, false);
        return new CourseViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull CourseViewHolder holder, int position) {
        Course course = mCourseList.get(position);
        // Glide 加载课程封面
        Glide.with(mContext)
                .load(course.getCoverUrl())
                .placeholder(R.drawable.placeholder)
                .error(R.drawable.error)
                .into(holder.ivCover);

        holder.tvTitle.setText(course.getTitle());
        holder.tvTeacher.setText("讲师：" + course.getTeacher());
        holder.tvDifficulty.setText("难度：" + course.getDifficulty());
        holder.rbScore.setRating(course.getScore());

        // 点击事件
        holder.itemView.setOnClickListener(v -> {
            if (mListener != null) {
                mListener.onCourseClick(course.getCourseId());
            }
        });
    }

    @Override
    public int getItemCount() {
        return mCourseList.size();
    }

    public static class CourseViewHolder extends RecyclerView.ViewHolder {
        ImageView ivCover;
        TextView tvTitle;
        TextView tvTeacher;
        TextView tvDifficulty;
        RatingBar rbScore;

        public CourseViewHolder(@NonNull View itemView) {
            super(itemView);
            ivCover = itemView.findViewById(R.id.iv_course_cover);
            tvTitle = itemView.findViewById(R.id.tv_course_title);
            tvTeacher = itemView.findViewById(R.id.tv_course_teacher);
            tvDifficulty = itemView.findViewById(R.id.tv_course_difficulty);
            rbScore = itemView.findViewById(R.id.rb_course_score);
        }
    }

    // 课程点击接口
    public interface OnCourseClickListener {
        void onCourseClick(int courseId);
    }

    public void setOnCourseClickListener(OnCourseClickListener listener) {
        mListener = listener;
    }
}